import subprocess

# 测试1
subprocess.run(["ls", "-l"])
""" 
total 16
-rwxrwxr-x 1 liuj liuj 320 Dec 10 16:04 1_subprocess_获取执行过程与结果.py
-rwxrwxr-x 1 liuj liuj 499 Dec 10 16:04 2_subprocess_实时获取输出.py
-rw-rw-r-- 1 liuj liuj 458 Dec 10 16:04 3_subprocess_check_outpu获取命令结果.py
-rw-rw-r-- 1 liuj liuj 241 Dec 10 16:04 4_subprocess.run_运行shell命令.py
CompletedProcess(args=['ls', '-l'], returncode=0)
"""

# 测试2: shell模式执行
subprocess.run(["ls -l /dev/null"], shell=True)
""" 
subprocess.run(["ls -l /dev/null"],shell=True)
crw-rw-rw- 1 root root 1, 3 Dec 12 09:38 /dev/null
CompletedProcess(args=['ls -l /dev/null'], returncode=0)
"""


# 测试3: 结果不为0时抛出异常
subprocess.run(["ls -l /dev/123"], shell=True, check=True)
""" 
ls: cannot access '/dev/123': No such file or directory
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.10/subprocess.py", line 526, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['ls -l /dev/123']' returned non-zero exit status 2.
"""

# 测试4: 获取执行过程
subprocess.run(["ls -l /dev/null"], shell=True, check=True, capture_output=True)
""" 过程在 stdout, stderr:
CompletedProcess(args=['ls -l /dev/null'], returncode=0, stdout=b'crw-rw-rw- 1 root root 1, 3 Dec 12 09:38 /dev/null\n', stderr=b'')
"""